package com.ruoyi.web.controller.huiyuan;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Attachements;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.IAttachementsService;
import com.ruoyi.system.service.IHuiyuanService;
import com.ruoyi.web.controller.util.UID;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Huiyuan;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;

/**
 * 会员 信息操作处理
 * 
 * @author chengenjiang
 * @date 2019-07-16
 */
@Controller
@RequestMapping("/system/huiyuan2")
public class HuiyuanController2 extends BaseController
{
    private String prefix = "system/huiyuan2";

	@Autowired
	private IHuiyuanService huiyuanService;
	@Autowired
	private IAttachementsService attachementsService;
	
	@RequiresPermissions("system:huiyuan2:view")
	@GetMapping()
	public String huiyuan()
	{
	    return prefix + "/huiyuan2";
	}
	
	/**
	 * 查询会员列表
	 */
	@RequiresPermissions("system:huiyuan2:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Huiyuan huiyuan)
	{
		startPage();
        List<Huiyuan> list = huiyuanService.selectHuiyuanList(huiyuan);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出会员列表
	 */
	@RequiresPermissions("system:huiyuan2:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Huiyuan huiyuan)
    {
    	List<Huiyuan> list = huiyuanService.selectHuiyuanList(huiyuan);
        ExcelUtil<Huiyuan> util = new ExcelUtil<Huiyuan>(Huiyuan.class);
        return util.exportExcel(list, "huiyuan");
    }
	
	/**
	 * 新增会员
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}

	public MultiValueMap<String, MultipartFile> getFiles(HttpServletRequest request) {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			MultiValueMap<String, MultipartFile> multipartFiles = multiRequest.getMultiFileMap();
			return multipartFiles;
		}
		return null;
	}




	/**
	 * 新增保存会员
	 */
	@RequiresPermissions("system:huiyuan2:add")
	@Log(title = "会员", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(HttpServletRequest request, Huiyuan huiyuan , MultipartFile[] files)
	{

		if (files != null && files.length > 0) {
			for (MultipartFile file : files) {

				Map<String, Object> fileInfo = saveFile(request,file);
				if (fileInfo != null) {
					Attachements attachement = new Attachements();
					attachement.setBeizhu(huiyuan.getUid());
					SysUser user = getSysUser();
					attachement.setModifyId(String.valueOf(user.getUserId()));
					attachement.setBeizhu(huiyuan.getUid());
					attachement.setStatus(0);
					attachement.setCreateId(String.valueOf(user.getUserId()));

					attachement.setMc(fileInfo.get("name").toString());
					attachement.setPath(fileInfo.get("path").toString());
					attachement.setSuffix(fileInfo.get("suffix").toString());
					attachement.setLen(fileInfo.get("size").toString());

					attachementsService.insertAttachements(attachement);

				}
			}
		}
		return toAjax(huiyuanService.insertHuiyuan(huiyuan));
	}

	/**
	 * 修改会员
	 */
	@GetMapping("/edit/{huiyuanId}")
	public String edit(@PathVariable("huiyuanId") Integer huiyuanId, ModelMap mmap)
	{
		Huiyuan huiyuan = huiyuanService.selectHuiyuanById(huiyuanId);
		Attachements attachement = new Attachements();
		attachement.setBeizhu(huiyuan.getUid());
		List<Attachements>attachements = attachementsService.selectAttachementsList(attachement);
		mmap.put("attachements",attachements);
		mmap.put("huiyuan", huiyuan);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存会员
	 */
	@RequiresPermissions("system:huiyuan2:edit")
	@Log(title = "会员", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(HttpServletRequest request, Huiyuan huiyuan , MultipartFile[] files)
	{
		if (files != null && files.length > 0) {
			for (MultipartFile file : files) {

				Map<String, Object> fileInfo = saveFile(request,file);
				if (fileInfo != null) {
					Attachements attachement = new Attachements();
					attachement.setBeizhu(huiyuan.getUid());
					SysUser user = getSysUser();
					attachement.setModifyId(String.valueOf(user.getUserId()));
					attachement.setBeizhu(huiyuan.getUid());
					attachement.setStatus(0);
					attachement.setCreateId(String.valueOf(user.getUserId()));

					attachement.setMc(fileInfo.get("name").toString());
					attachement.setPath(fileInfo.get("path").toString());
					attachement.setSuffix(fileInfo.get("suffix").toString());
					attachement.setLen(fileInfo.get("size").toString());

					attachementsService.insertAttachements(attachement);

				}
			}
		}
		return toAjax(huiyuanService.updateHuiyuan(huiyuan));
	}
	
	/**
	 * 删除会员
	 */
	@RequiresPermissions("system:huiyuan2:remove")
	@Log(title = "会员", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(huiyuanService.deleteHuiyuanByIds(ids));
	}

	private File toImage(String imgStr){
		try {
			if (StringUtils.isNotBlank(imgStr)) {
				String suffix = "jpg";
				if (imgStr.indexOf("data") > -1) {
					suffix = imgStr.substring(0, imgStr.lastIndexOf(","));
					suffix = suffix.substring(suffix.lastIndexOf("/")+1, suffix.lastIndexOf(";"));
					if (suffix.toUpperCase().equals("JPEG")) {
						suffix = "jpg";
					}
					imgStr = imgStr.substring(imgStr.lastIndexOf(",")+1);
				}
				byte[] b = new BASE64Decoder().decodeBuffer(imgStr);
				for (byte c : b) {
					if (c < 0) {
						c += 256;
					}
				}
				File file = File.createTempFile(new Random().nextInt(10000000)+"","."+suffix);
				OutputStream out = new FileOutputStream(file);
				out.write(b);
				out.flush();
				out.close();
				return file;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
